<?php
error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT & ~E_NOTICE );

require_once(__DIR__ . '/vendor/autoload.php');
require_once(__DIR__ . '/config.php');
set_time_limit(0);

/**
 * 读取云主机列表
 */

function getCvms() {
	
	global $config;

	$se = QcloudApi::load(QcloudApi::MODULE_CVM, $config);
	$package = [
		"Version" => "2017-03-12",
		"Filters.1.Name" => "instance-charge-type",
		"Filters.1.Values.1" => "POSTPAID_BY_HOUR"
	];

	$data = $se->DescribeInstances($package);
	$resp = $data['Response'];
	return $resp;
}


function getBackends() {
	global $config;
	$se = QcloudApi::load(QcloudApi::MODULE_LB, $config);

	$package = [
		"loadBalancerId" => $config['loadBalancerId'],
		"listenerId" => $config['listenerId']
	];

	$resp = $se->DescribeForwardLBBackends($package);

	$rules = current($resp['data'])['rules'];
	if ( !is_array($rules) ) {
		return ["TotalCount"=>0, "InstanceSet"=>[]];
	}

	$backends = current($rules)['backends'];
	if ( !is_array($backends) ) {
		return ["TotalCount"=>0, "InstanceSet"=>[]];
	}

	foreach ($backends as $idx=>$bd ) {
		$backends[$idx]['InstanceId'] = $bd['unInstanceId'];
	}

	return [
		"TotalCount" => count($backends),
		"InstanceSet" => $backends
	];

}



/**
 * 读取云主机状态
 * @param  [type] $cvm_id [description]
 * @return [type]         [description]
 */
function getCvmStatus( $cvm_id ) {
	global $config;

	$se = QcloudApi::load(QcloudApi::MODULE_CVM, $config);
	$package = [
		"Version" => "2017-03-12",
		"InstanceIds.1" => $cvm_id	
	];


	$data = $se->DescribeInstancesStatus($package);
	$resp = $data['Response'];
	$statusSet = $resp['InstanceStatusSet'];
	if ( !is_array($statusSet) ) {
		return false;
	}

	$status = end( $statusSet );
	if ( !is_string($status['InstanceState']) ) {
		return false;
	}

	return $status['InstanceState'];

}


/**
 * 创建一台云主机
 */
function createCvm() {
	
	global $config;

	lock();
	$se = QcloudApi::load(QcloudApi::MODULE_CVM, $config);
	$package = [
		"Version" => "2017-03-12",
		"InstanceChargeType" => "POSTPAID_BY_HOUR",
		"ImageId" => $config['ImageId'],
		"InstanceName" => "伸缩系统自动创建",
		"InternetAccessible.InternetMaxBandwidthOut" => 1,
		// "InternetAccessible.PublicIpAssigned" => 'FALSE',
		"SecurityGroupIds.1" => $config['SecurityGroupId'],
		"Placement.Zone" => $config['DefaultZone']
	];

	$data = $se->RunInstances($package);
	$resp = $data['Response'];
	if ( !is_array($resp['InstanceIdSet']) ) {
		print_r($resp );
		return false;
	}

	$cvm_id = end($resp['InstanceIdSet']);

	// 等待创建完成
	while(1) {
		echo "检查云主机状态...";
		$status = getCvmStatus( $cvm_id );
		echo $status . "\n";

		if ( $status === 'RUNNING' ||  $status === false ) {
			break;
		}
		sleep(30);
	}

	unlock();
	return end($resp['InstanceIdSet']);
}


/** 
 * 销毁设备
 */
function destoryCvm( $cvm_id ) {
	global $config;

	lock();
	$se = QcloudApi::load(QcloudApi::MODULE_CVM, $config);
	$package = [
		"Version" => "2017-03-12",
		"InstanceIds.1" => $cvm_id	
	];


	$data = $se->TerminateInstances($package);
	$resp = $data['Response'];
	if( !isset($resp['RequestId']) ) {
		return false;
	}

	// 冷却时间5分钟
	echo "锁定5分钟....";
	sleep(300); 
	echo "完成\n";

	unlock();
	return true;
}



/**
 * 添加到负载均衡器 
 * 
 * @see https://www.qcloud.com/document/product/214/8988
 * @param  [type] $cvm_id [description]
 * @return [type]         [description]
 */
function bindtoLB( $cvm_id ) {
	global $config;

	lock();
	$se = QcloudApi::load(QcloudApi::MODULE_LB, $config);

	$package = [
		"loadBalancerId" => $config['loadBalancerId'],
		"listenerId" => $config['listenerId'],
		"backends.1.instanceId" => $cvm_id,
		"backends.1.port" => 80,
		"backends.1.weight" => 10
	];

	$data = $se->RegisterInstancesWithForwardLBSeventhListener($package);
	if ($data['codeDesc'] == 'Success') {

		renderMonitor();

		// 冷却时间5分钟
		echo "锁定5分钟....";
		sleep(300); 
		echo "完成\n";
		unlock();
		return true;
	}

	print_r($data);
	return false;
}


/**
 * 从负载均衡解绑
 * @param  [type] $cvm_id [description]
 * @return [type]         [description]
 */
function removeFromLB( $cvm_id ){
	
	global $config;
	lock();
	$se = QcloudApi::load(QcloudApi::MODULE_LB, $config);

	$package = [
		"loadBalancerId" => $config['loadBalancerId'],
		"listenerId" => $config['listenerId'],
		"backends.1.instanceId" => $cvm_id,
		"backends.1.port" => 80
	];

	$data = $se->DeregisterInstancesFromForwardLB($package);
	if ($data['codeDesc'] == 'Success') {
		renderMonitor();
		unlock();
		return true;
	}

	var_dump($data);

	return false;
}

/**
 * 锁定防止重复创建
 * @return [type] [description]
 */
function lock() {
	$path = sys_get_temp_dir() . "/scale.lock";
	file_put_contents($path, 'TRUE');
}

/**
 * 解锁
 * @return [type] [description]
 */
function unlock() {
	$path = sys_get_temp_dir() . "/scale.lock";
	file_put_contents($path, 'FALSE');
}



/**
 * 检查锁
 * @return [type] [description]
 */
function islock() {
	$path = sys_get_temp_dir() . "/scale.lock";
	if ( file_exists($path) ) {
		$string = file_get_contents($path);
		if ( $string == 'TRUE') {
			return true;
		}
	}
	return false;
}


/**
 * 生成监控模板
 * @return [type] [description]
 */
function renderMonitor() {
	global $config;
	echo "刷新监控页面 ... ";
	$cvms = getBackends();
	$insts = (!is_array($cvms['InstanceSet'])) ? [] : $cvms['InstanceSet'];
	$ips = [];
	foreach ($insts as $inst ) {
		$ip = end( $inst['wanIpSet']);
		array_push($ips, $ip);
	}

	ob_start();
	require( __DIR__ . '/tpl/mt.html');
	$html = ob_get_contents();
    ob_end_clean();

    @file_put_contents($config['netdata'], $html);
    exec("chown netdata:netdata {$config['netdata']}");
    echo "完成\n";

    return $html;
}



/**
 * 最近5分钟内网入包量
 * @param  [type] $cvm_id [description]
 * @return [type]         [description]
 */
function getTraffic( $cvm_id ) {
	global $config; 
	$se = QcloudApi::load(QcloudApi::MODULE_MONITOR, $config);

	$package = [
		"namespace" => "qce/cvm",
		"metricName" => "lan_inpkg",  // 内网入包量
		"dimensions.0.name" =>  "unInstanceId",
		"dimensions.0.value" => $cvm_id,
		"period" => 60,
		"startTime" => date('Y-m-d H:i:s', time() - 60 ),
		"endTime" => date('Y-m-d H:i:s' )
	];

	$resp = $se->GetMonitorData( $package );
	

	foreach ($resp['dataPoints'] as $idx => $val) {
		if ( $val == "") {
			unset($resp['dataPoints'][$idx]);
		}
	}

	$cnt = (count($resp['dataPoints']) == 0) ? 1 : count($resp['dataPoints']);
	$resp['data'] = array_sum($resp['dataPoints']) / $cnt;

	return $resp;
	
}